import React, {useEffect, useState} from 'react';
import {message, Spin} from "antd";
import './index.css'
import {useLocation} from "react-router-dom";
import http from "../../../util/http";

//设置默认内容
const defaultExport = `<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>文档id无效</h1>
</body>
</html>`;

function Html(props) {
    const location = useLocation();
    const state = location.state || {}
    // 优先选择 props.params
    const propParams = props.params;
    let docId = -1
    if (propParams !== undefined && propParams.docId !== undefined) {
        docId = propParams.docId || -1
    }else{
        // const params =  state.params ||  {}
        docId = state.params.docId || -1
    }

    //文章数据
    const [data, setData] = useState({});
    //加载状态
    const [loading, setLoading] = useState(false);
    //附件列表
    const [files, setFiles] = useState([])
    useEffect(() => {
        setData({})
        setLoading(true)
        http.doGet('/doc/gethtml', {id: docId}).then(res => {
            if (res.status === 200) {
                setData({title: res.title, content: res.content})
                setFiles(res.file)
            } else {
                setData({title: "", content: defaultExport})
            }
            setLoading(false)
        }).catch(reason => {
            message.error(reason.message)
            setData({title: "", content: ""})
            setLoading(false)
        })
    }, [docId])

    function toDownload(fileId) {
        if (fileId) {
            window.open('/doc/sg/download?fileid=' + fileId)
        }
    }

    return (
        <div className="portal-html-main">
            <Spin spinning={loading}>
                <div className="portal-html-title">{data.title}</div>
                <div className="portal-html-content">
                    <div dangerouslySetInnerHTML={{__html: data.content}}/>
                </div>
                <div className="portal-files-list">
                    <div className="portal-files-list-title">{files.length > 0 ? "附件:" : ""}</div>
                    <div className="portal-files-list-content">
                        {
                            files.map((item, index) => {
                                return (
                                    <div className="portal-files-list-item" key={index}
                                         onClick={() => toDownload(item.fileid)}>
                                        {item.filename}
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </Spin>
        </div>
    );
}

export default Html;